package com.wteam.dragon.system.config.mybatisplus;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.wteam.dragon.system.util.UserUtil;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.sql.Timestamp;

/**
 * 自动填充功能
 * @author 陈晓辉
 * @date 2020/3/7 18:04
 */
@Component
public class MetaHandler implements MetaObjectHandler {

    /**
     * 创建数据执行
     *
     * @param metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        Long userId = UserUtil.getCurrentUserId();
        this.setFieldValByName("createTime", new Timestamp(System.currentTimeMillis()), metaObject);
        this.setFieldValByName("updateTime", new Timestamp(System.currentTimeMillis()), metaObject);
        if(userId != null){
            this.setFieldValByName("createId", userId, metaObject);
            this.setFieldValByName("updateId", userId, metaObject);
        }
    }

    /**
     * 更新数据执行
     *
     * @param metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        Long userId = UserUtil.getCurrentUserId();
        this.setFieldValByName("updateTime", new Timestamp(System.currentTimeMillis()), metaObject);
        if(userId != null){
            this.setFieldValByName("updateId", userId, metaObject);
        }
    }
}
